<template>
  <div>
    <el-form :model="editRoleForm" :rules="rules" ref="editRoleRef" label-width="100px">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="editRoleForm.roleName"></el-input>
      </el-form-item>
      <el-form-item label="角色描述">
        <el-input v-model="editRoleForm.roleDesc"></el-input>
      </el-form-item>
    </el-form>
    <div class="btn">
      <el-button @click="closeDialog">取 消</el-button>
      <el-button type="primary" @click="editRole">确 定</el-button>
    </div>
  </div>
</template>

<script>
export default {
  props: [
    'id'
  ],
  data () {
    return {
      roleId: this.id,
      // 修改角色规则
      rules: {
        roleName: [
            { required: true, message: '请输入角色名称', trigger: 'blur' },
            { min: 3, max: 5, message: '长度在 3 到 10 个字符', trigger: 'blur' }
          ]
      },
      editRoleForm: {
        roleName: '',
        roleDesc: ''
      }
    }
  },
  mounted() {
    this.getRoles(this.roleId)
    this.send()
    this.sendRefs()
  },

  methods: {
    send() {
      this.$emit('changeTitle', '修改角色')
    },
    // 向父组件发送子组件的refs
    sendRefs() {
      this.$emit('refs', 'editRoleRef')
    },
    async getRoles(id) {
      console.log(id)
      this.roleId = id
      const that = this
      const { data: res } = await this.$http.get('roles/' + id)
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色数据失败！')
      }
      this.$message.success('获取角色成功！')
      that.editRoleForm.roleName = res.data.roleName
      that.editRoleForm.roleDesc = res.data.roleDesc
    },
     // 点击取消按钮关闭对话框
    closeDialog() {
      this.$refs.editRoleRef.resetFields()
      this.editRoleForm.roleDesc = ''
      this.$emit('close', false)
    },
    // 点击确认按钮触发的事件
    editRole() {
      this.$refs.editRoleRef.validate(async valid => {
        if (!valid) return // 预校验失败
        const { data: res } = await this.$http.put('roles/' + this.roleId, this.editRoleForm)
        if (res.meta.status !== 200) {
          return this.$message.error('修改角色失败')
        }
        this.$message.success('修改角色成功')
        this.$emit('close', false)
      })
    }
  }
}
</script>

<style>
.btn{
  float: right;
  margin-top: 15px;
}
</style>
